package com.edu.cq02.exceptionhandler;

import com.edu.cq02.controller.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ErrorExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        System.out.println(e);
        System.out.println("ErrorExceptionResolver");

        HandlerMethod method=(HandlerMethod)o;
        //处理AJAX请求异常
        if(method.hasMethodAnnotation(ResponseBody.class)){
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
            httpServletResponse.setCharacterEncoding("UTF-8");
            ObjectMapper mapper=new ObjectMapper();
            ResultData result=new ResultData();
            result.setCode(-1);
            result.setMsg("系统出现了错误，请联系大神");
            try {
                httpServletResponse.getWriter().write(mapper.writeValueAsString(result));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return new ModelAndView();
        }else{
            ModelAndView mv = new ModelAndView();
            mv.setViewName("error");
            return mv;
        }
    }
}
